package com.sf.fy.uav.common.utils;

import com.sf.fy.uav.common.request.operate.FileAddRequest;
import io.swagger.v3.oas.annotations.Parameter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Iterator;


/**
 * @author LTQ
 */
@Component
public class UploadToOssUtils {

    private final static Logger logger = LoggerFactory.getLogger(UploadToOssUtils.class);


    @Autowired
    private SfOssClientUtil sfOssClientUtil;


    @Value("${oss.bucket:/applet/banner/}")
    private String ossBucket;

    @Value("${oss.public-path:https://sit-ie-uocs-core-shenzhen-xili1-oss.sit.sf-express.com/v1.2/AUTH_sit-IE-UOCS-CORE/sfosspublic001}")
    private String ossPublicPath;

    @Value("${oss.businessBucket:/applet/business/}")
    private String businessOssBucket;

    @Value("${oss.businessBucket:/applet/commodity/}")
    private String commodityOssBucket;

    @Value("${oss.businessBucket:/applet/popUpScreen/}")
    private String popUpScreenOssBucket;

    @Value("${oss.businessBucket:/applet/businessLicense/}")
    private String businessLicenseOssBucket;


    @Value("${file.path:/usr/local/system/}")
    private String baseUrl;

    @Autowired
    private PhoneEncoderUtil phoneEncoderUtil;

    @PostMapping("picture")
    @CrossOrigin
    @Parameter(name = "subject", description = "取值含义business上传商家图片,commodity上传商品图片")
    public FileAddRequest uploadPicture(HttpServletRequest request, HttpServletResponse response, @RequestParam String subject, @RequestParam(required = false) String compressionQuality) throws Exception {

        FileAddRequest fileAddRequest = new FileAddRequest();
        String fileName = request.getParameter("fileName");

        if (!fileName.contains(".jpg") && !fileName.contains(".png") && !fileName.contains(".gif") && !fileName.contains(".jpeg")) {
            throw new RuntimeException("只能上传jpg/png/gif/jpeg");
        } else {
            String[] fileNames = fileName.split("\\.");
            fileName = System.currentTimeMillis() + "-" + phoneEncoderUtil.encryptString(fileNames[0]) + "." + fileNames[1];
        }
        fileAddRequest.setFileName(fileName);
        String fileSavePath = baseUrl;

        if (subject.equals("business")) {
            fileSavePath += "business/cover/";
        } else if (subject.equals("commodity")) {
            fileSavePath += "commodity/cover/";
        } else if ("popUpScreen".equals(subject)) {
            fileSavePath += "popUpScreen/cover/";
        } else if ("businessLicense".equals(subject)) {
            fileSavePath += "businessLicense/cover/";
        } else {
            fileSavePath += "banner/cover/";
        }
        //设置编码
        request.setCharacterEncoding("utf-8");
        File dir = new File(fileSavePath);
        System.out.println(dir.getPath());
        //创建一个名为当前年月日的文件夹，在文件夹中存放图片
        if (!dir.isDirectory()) {
            dir.mkdirs();
        }
        try {
            StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request;
            //获取formData的值
            Iterator<String> iterator = req.getFileNames();

            while (iterator.hasNext()) {
                MultipartFile file = req.getFile(iterator.next());
                //真正写到磁盘上
                File file1 = new File(fileSavePath + fileName);
                file.transferTo(file1);
                logger.info("path-------->" + fileSavePath + fileName);
//                if (!ObjectUtils.isEmpty(compressionQuality)) {
//                    ImageCompressor.compressImage(fileSavePath + fileName, fileSavePath + fileName, Float.parseFloat(compressionQuality));
//                }
                InputStream in = new FileInputStream(file1);
                String filePath;
                if (subject.equals("business")) {
                    filePath = businessOssBucket + fileName;
                } else if (subject.equals("commodity")) {
                    filePath = commodityOssBucket + fileName;
                } else if ("popUpScreen".equals(subject)) {
                    filePath = popUpScreenOssBucket + fileName;
                } else if ("businessLicense".equals(subject)) {
                    filePath = businessLicenseOssBucket + fileName;
                } else {
                    filePath = ossBucket + fileName;
                }

                sfOssClientUtil.uploadV1(filePath, in);
                System.out.println(file1.getPath());
                fileAddRequest.setFilePath(filePath);
                file1.delete();
            }
            return fileAddRequest;
        } catch (Exception e) {
            System.out.println(e);
            throw e;
        }
    }

}
